<?php
/* $Id: cart.php 14 2009-04-11 17:40:34Z ronan $ */
$basesite=$_SERVER['PHP_SELF'];
require("common.php");
require("auth.php");
require("header.php");

if(isset($_GET['f'])) $f=$_GET['f']; else if(isset($_POST['f'])) $f=$_POST['f']; else $f='view';
if(isset($_GET['id'])) $id=$_GET['id']; else if(isset($_POST['id'])) $id=$_POST['id'];

if($f=='updateqty') {
	$orders = Query("SELECT * FROM orders WHERE customerID='$uidnum' AND status='in cart'");
	$numrows = mysql_num_rows($orders);
	for($i=0;$i<$numrows;$i++) {
		$qty = stripCommas($_POST[$i.'_qty']);
		$isBlueprint=(mysql_result($orders,$i,'usingStock')==3);
		if($isBlueprint)  {//BLUEPRINT
			$item = Query("SELECT * FROM blueprints WHERE id='".mysql_result($orders,$i,'typeID')."' LIMIT 1");
		} else $item = getItemById(mysql_result($orders,$i,'typeID'));
		$numAvailable=mysql_result($item, 0, 'numAvailable');
		$quantityModifier=mysql_result($orders,$i,'quantityModifier');
		if(!$isBlueprint) $isBuildable=mysql_result($item,0,'isBuildable');
		if(!$isBlueprint) $isSpecialOrderable=mysql_result($item,0,'isSpecialOrderable');
		$name=mysql_result($item,0,'typeName');
		if($qty > $numAvailable && $isBlueprint) {
			echo "We have $numAvailable".($quantityModifier==1?'':"x".$quantityModifier)." \"$name\"s in stock - you cannot order more than this. Quantity not changed.<br />\n";
			continue;
		}
		if($qty < 1) {
			echo "You cannot have an order of <1 quantity. \"$name\" quantity not changed.";
			continue;
		}
		if($qty > $maxQuantity) {
			echo "You cannot have an order of this massive a quantity. \"$name\" quantity not changed.";
			continue;
		}
		if(!is_number($qty)) {
			echo "You cannot have an order of a non-numeric quantity. \"$name\" quantity not changed.";
			continue;
		}
		if($qty > $numAvailable && !$isBlueprint && !$isBuildable && $isSpecialOrderable) {
			echo "We have $numAvailable x $quantityModifier \"$name\"s in stock, and we cannot build more. <font color=\"yellow\">Any quantity beyond what we have in stock will be placed as a special order.</font><br />\n";
		}
		if($qty > $numAvailable && !$isBlueprint && !$isBuildable && !$isSpecialOrderable) {
			echo "We have $numAvailable x $quantityModifier \"$name\"s in stock, and we cannot build more. We also cannot special order any more of this item. Quantity not changed.<br />\n";
			continue;
		}
		if($qty > $numAvailable && !$isBlueprint && $isBuildable) {
			echo "We have $numAvailable".($quantityModifier==1?'':"x".$quantityModifier)." \"$name\"s in stock. <font color=\"yellow\">Any quantity beyond what we have in stock will be placed as a build order.</font><br />\n";
		}
		$priceTotal=$qty*$_POST[$i.'_ppu'];
		$results=Query("UPDATE orders SET quantity='".$qty."', priceTotal='$priceTotal' WHERE id='".$_POST[$i.'_id']."' LIMIT 1");	
	}
}
if($f=='remove') {
	if(!isset($id)) {echo "Error: No id to remove";}
	$results=Query("DELETE FROM orders WHERE id='$id' LIMIT 1");
}
if($f=='removeall') {
	$results=Query("DELETE FROM orders WHERE customerID='$uidnum' AND status='in cart'");
}
else if($f=='order') {
	$orders= Query("SELECT * FROM orders WHERE customerID='$uidnum' AND status='in cart'");
	$numrows = mysql_num_rows($orders);
	for($i=0;$i<$numrows;$i++) {
		$isBlueprint=(mysql_result($orders,$i,'usingStock')==3);
		if($isBlueprint)  {//BLUEPRINT
			$item = Query("SELECT * FROM blueprints WHERE id='".mysql_result($orders,$i,'typeID')."' LIMIT 1");
		} else $item = getItemById(mysql_result($orders,$i,'typeID'));
		$numAvailable=mysql_result($item, 0, 'numAvailable');
		if(!$isBlueprint) $isBuildable=mysql_result($item,0,'isBuildable');
		if(!$isBlueprint) $isSpecialOrderable=mysql_result($item,0,'isSpecialOrderable');
		$qty = mysql_result($orders,$i,'quantity');
		$name=mysql_result($item,0,'typeName');
		
		if(($numAvailable<=0 && !$isBuildable && $isSpecialOrderable) || $isBlueprint) {//SPECIAL ORDER OR BLUEPRINT
			if($isBlueprint) {
				$resultsItemUpdate = Query("UPDATE blueprints SET numAvailable='".($numAvailable-$qty)."' WHERE id=".mysql_result($orders,$i,'typeID')." LIMIT 1");
				$bpname = mysql_result($orders,$i,'typeName')." (ME: ".mysql_result($item,0,'ME').", PE: ".mysql_result($item,0,'PE').", ".mysql_result($item,0,'runs')." runs)";
				$resultsBPNameUpdate = Query("UPDATE orders SET typeName='$bpname' WHERE id='".mysql_result($orders,$i,'id')."' LIMIT 1");	
			}
			$resultsUpdate = Query("UPDATE orders SET timePlaced=NOW(), status='awaiting processing', usingStock='".($isBlueprint?3:2)."' WHERE id='".mysql_result($orders,$i,'id')."' LIMIT 1");
			continue;
		}
		if($qty > $numAvailable) {
			if(!$isSpecialOrderable && !$isBuildable) {
				echo "We cannot build or special order \"$name\"s, and you are trying to order more of them than we have in stock. This item was not ordered and has been removed from your cart.<br />\n";
				Query("DELETE FROM orders WHERE id='".mysql_result($orders,$i,'id')."' LIMIT 1");
				continue;
			}
			if(!$isBuildable) { //SPECIAL ORDER SPLIT
				echo "We have split your order of $qty \"$name\"s because we only have $numAvailable in stock. The rest are in a separate <font color=\"yellow\">special order</font>.<br />\n";
				$fields=array();
				$dqueryr=Query("DESC orders");
				while($line = mysql_fetch_array($dqueryr)) {
					array_push($fields, $line['Field']);
				}	
				$ks=$vs='';
				foreach($fields as $f) {
					if($f=='id' || $f=='timeCompleted' || $f=='producerID' || $f=='producerName') continue;
					$v=mysql_result($orders,$i,$f);
					if(isset($commatemp)) {$ks.=', '; $vs.=', ';} else $commatemp=true;
					if($f=='quantity') $v=$qty-$numAvailable;
					if($f=='priceTotal') $v=($qty-$numAvailable)*mysql_result($orders,$i,'pricePerUnit');
					if($f=='usingStock') $v=2;
					if($f=='timePlaced') { $ks.=$f; $vs.="NOW()"; continue; }
					if($f=='status') $v='awaiting processing';
					$ks.=$f; $vs.="'$v'";
				}
				$resultsInsert = Query("INSERT INTO orders($ks) VALUES($vs)");
				$resultsUpdate = Query("UPDATE orders SET quantity='$numAvailable', priceTotal='".(mysql_result($orders,$i,'pricePerUnit')*$numAvailable)."', usingStock='1', timePlaced=NOW(), status='awaiting processing' WHERE id='".mysql_result($orders,$i,'id')."' LIMIT 1");
				$resultsItemUpdate = Query("UPDATE items SET numAvailable='0' WHERE typeID=".mysql_result($orders,$i,'typeID')." LIMIT 1");
				//$results=Query("DELETE FROM orders WHERE id='".mysql_result($orders,$i,'id')."' LIMIT 1");
				continue;
			} else if ($numAvailable>0){ //We can build it split
				echo "We have split your order of $qty \"$name\"s because we only have $numAvailable in stock. The rest are in a separate build order.<br />\n";
				$fields=array();
				$dqueryr=Query("DESC orders");
				while($line = mysql_fetch_array($dqueryr)) {
					array_push($fields, $line['Field']);
				}	
				$ks=$vs='';
				foreach($fields as $f) {
					if($f=='id' || $f=='timeCompleted' || $f=='producerID' || $f=='producerName') continue;
					$v=mysql_result($orders,$i,$f);
					if(isset($commatemp)) {$ks.=', '; $vs.=', ';} else $commatemp=true;
					if($f=='quantity') $v=$qty-$numAvailable;
					if($f=='priceTotal') $v=($qty-$numAvailable)*mysql_result($orders,$i,'pricePerUnit');
					if($f=='timePlaced') { $ks.=$f; $vs.="NOW()"; continue; }
					if($f=='status') $v='awaiting producer';
					$ks.=$f; $vs.="'$v'";
				}
				$resultsInsert = Query("INSERT INTO orders($ks) VALUES($vs)");
				$resultsUpdate = Query("UPDATE orders SET quantity='$numAvailable', priceTotal=quantity*pricePerUnit, usingStock='1', timePlaced=NOW(), status='awaiting processing' WHERE id='".mysql_result($orders,$i,'id')."' LIMIT 1");
				$resultsItemUpdate = Query("UPDATE items SET numAvailable='0' WHERE typeID=".mysql_result($orders,$i,'typeID')." LIMIT 1");				
			}
		} else if($numAvailable>0) {
			$resultsItemUpdate = Query("UPDATE items SET numAvailable='".($numAvailable-$qty)."' WHERE typeID=".mysql_result($orders,$i,'typeID')." LIMIT 1");
			$resultsUpdate = Query("UPDATE orders SET usingStock='1', timePlaced=NOW(), status='awaiting processing' WHERE id='".mysql_result($orders,$i,'id')."' LIMIT 1");
		}
	}
	$results = Query("UPDATE orders SET status='awaiting producer', timePlaced=NOW() WHERE customerID='$uidnum' AND status='in cart'");
	echo "\n<br />Order successfully placed!<br />\n";
	require('footer.php');
	exit;
}

$orders = Query("SELECT * FROM orders WHERE customerID='$uidnum' AND status='in cart'");
if(!mysql_num_rows($orders)) {
	echo "Your cart is empty!<br /><br />\n\n";
} else {
	$total=0;
	$i=0;
	echo "<form method=\"POST\" action=\"cart.php\">\n";
	echo "<table border=0 cellspacing=0 cellpadding=2><tr><td align=\"center\" width=\"75\"><b>Item</b></td><td align=\"center\" width=\"125\"><b>Qty.</b></td><td align=\"center\" width=\"90\"><b>Per Unit</b></td><td align=\"center\" width=\"90\"><b>Total</b></td><td align=\"center\" width=\"50\"><b>Options</b></td></tr>\n";
	while ($line = mysql_fetch_array($orders, MYSQL_ASSOC)) {
		$total+=$line['priceTotal'];
		
		
		
		echo ($bgcolor?"<tr class=\"tablecolor1\">":"<tr class=\"tablecolor2\">");
		$bgcolor= !$bgcolor;
		$typeID=$line['typeID'];
		$gfx=getGraphicPath($typeID);
		$imgsize=getImgsize($typeID);
		
		if($line['usingStock']==3) $usingStock=3;
		else {
			$item=getItemById($line['typeID']);
			$usingStock = ((mysql_result($item,0,'numAvailable')==0&&mysql_result($item,0,'isBuildable')==0)?2:0);
		}
		echo "\t" .
				"<td width=\"$imgsize\"><img width=\"$imgsize\" height=\"$imgsize\" src=\"$gfx\" /></td>\t" .
    			"<td align=\"center\" width=\"75\">".($usingStock==2?'<font color="yellow">SPECIAL ORDER: ':'').$line['typeName'].($usingStock==2?'</font>':'')."</td>\t" .
    			"<td align=\"center\" width=\"125\">".generateHiddenFields(array($i."_ppu"=>$line['pricePerUnit'], $i."_id"=>$line['id']))."<input type=\"text\" size=\"6\" name=\"".$i."_qty\" value=\"".addCommas($line['quantity'])."\" />".($line['quantityModifier']==1?'':"x".addCommas($line['quantityModifier']))."</td>\t" .
    			"<td align=\"center\" width=\"90\">".addCommas($line['pricePerUnit'])." per ".addCommas($line['quantityModifier'])." </td>\t" .
    			"<td align=\"center\" width=\"90\">".addCommas($line['priceTotal'])."</td>\t" .
    			"<td align=\"center\" width=\"50\"><a href=\"cart.php?f=remove&id=".$line['id']."\">Remove</a></td>\t" .
    			"</tr>\n";
    	$i++;
	}
	echo "</table><br />\n" .
			"Total amount in cart: ".addCommas($total)." ISK<br />\n" .
			generateHiddenFields(array("f"=>"updateqty")) . "<input type=\"submit\" value=\"Update Quantities\" /></form>\t" .
			generateButton("Place Order", "GET", array("f"=>"order"))."\t" .
			generateButton("Empty Cart", "GET", array("f"=>"removeall")) . "\n";
}
require("footer.php");
?>
